package com.report.controller;

import cn.hutool.core.io.file.FileReader;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONPath;
import com.report.dto.Response;
import com.report.entity.ReportExportTemplate;
import com.report.entity.TablePlaceholder;
import com.report.service.ReportExportService;
import com.report.vo.ExportReportReq;
import com.report.vo.TablePlaceholderVo;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.FileNotFoundException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 报表导出
 */
@RestController
@RequestMapping("/api/reportExport")
public class ReportExportController {

    @Resource
    private ReportExportService reportExportService;

    /**
     * 上传报表导出模板
     *
     * @param reportExportTemplate
     * @return
     */
    @PostMapping("/addTemplate")
    public Response upload(@RequestBody ReportExportTemplate reportExportTemplate) {

        reportExportService.addReportExportTemplate(reportExportTemplate);
        return Response.success();
    }

    /**
     * 查询报表导出模板
     *
     * @param reportExportTemplate
     * @return
     */
    @PostMapping("/getTemplates")
    public Response getReportExportTemplate(@RequestBody ReportExportTemplate reportExportTemplate) {
        List<ReportExportTemplate> reportExportTemplates = reportExportService.findReportExportTemplate(reportExportTemplate);
        return Response.success(reportExportTemplates);
    }

    /**
     * 添加报表导出占位符
     *
     * @param placeholder
     * @return
     */
    @PostMapping("/addPlaceholder")
    public Response addPlaceholder(@RequestBody TablePlaceholder placeholder) {
        reportExportService.addPlaceholder(placeholder);
        return Response.success();
    }

    /**
     * 查询报表导出占位符
     *
     * @return
     */
    @PostMapping("/getPlaceholders")
    public Response getPlaceholders() {
        List<TablePlaceholderVo> placeholders = reportExportService.getPlaceholders();
        return Response.success(placeholders);
    }


    /**
     * 导出报表
     *
     * @param exportReportReq
     * @return
     */
    @PostMapping("/exportReport")
    public ResponseEntity<byte[]> exportReport(@RequestBody ExportReportReq exportReportReq) {

        try {
            StringBuilder fileName = new StringBuilder();

            // 调用服务层生成报表
            byte[] reportData = reportExportService.exportReport(exportReportReq, fileName);

            // 构建响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName.toString(), "UTF-8"));

            // 返回响应实体
            return new ResponseEntity<>(reportData, headers, HttpStatus.OK);
        } catch (Exception e) {
            // 异常处理
            throw new RuntimeException("导出报表失败", e);
        }

    }

    public static void main(String[] args) throws FileNotFoundException {

        FileReader fileReader = new FileReader("G:\\menu.json");
        String s = fileReader.readString();
        Set<String> placeholders = new HashSet<>();
        Set<String> table_names = new HashSet<>();
        List<Object> reads = JSONPath.read(s, "$.data", List.class);

        List<com.report.vo.node> nodes = new ArrayList<>();

        for (Object read : reads) {
            String id = JSONPath.read(read.toString(), "$.id", String.class);
            String pid = JSONPath.read(read.toString(), "$.pid", String.class);
            String tableName = JSONPath.read(read.toString(), "$.name", String.class);
            String playcehodler = tableName.replaceAll("[^\\u4e00-\\u9fa5\\d[a-zA-Z]\\-]", "").replaceAll("-", "_");


            String sql = "INSERT INTO `report_merge`.`table_placeholder`(`placeholder`, `table_name`, `p_id`, `row_id`) VALUES ('%s', '%s', %s, '%s');";
            System.out.println(String.format(sql, playcehodler, tableName, pid == null ? null : "'" + pid + "'", id));

            /*node node = new node();
            node.setId(id);
            node.setPid(pid);
            node.setName(tableName);
            nodes.add(node);*/
        }
        System.out.println(JSON.toJSON(nodes));



        /*if (placeholders.contains(playcehodler) || table_names.contains(tableName)) {
            System.out.println(playcehodler + ":" + tableName);
            System.out.println("-----------");
            break;
        }
        placeholders.add(playcehodler);
        table_names.add(tableName);

        String sql = "INSERT INTO `report_merge`.`table_placeholder`(`placeholder`, `table_name`) VALUES ('%s', '%s');";
        System.out.println(String.format(sql, playcehodler, tableName));*/


    }

}
